document.addEventListener('DOMContentLoaded', () => {
  const dropZone = document.getElementById('dropZone');
  const fileInput = document.getElementById('fileInput');
  const uploadButton = document.getElementById('uploadButton');
  const uploadStatus = document.getElementById('uploadStatus');

  // Prevent default drag behaviors
  ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
    dropZone.addEventListener(eventName, preventDefaults, false);
    document.body.addEventListener(eventName, preventDefaults, false);
  });

  // Highlight drop zone when dragging over it
  ['dragenter', 'dragover'].forEach(eventName => {
    dropZone.addEventListener(eventName, highlight, false);
  });

  ['dragleave', 'drop'].forEach(eventName => {
    dropZone.addEventListener(eventName, unhighlight, false);
  });

  // Handle dropped files
  dropZone.addEventListener('drop', handleDrop, false);

  // Handle click upload
  uploadButton.addEventListener('click', () => {
    fileInput.click();
  });

  fileInput.addEventListener('change', (e) => {
    handleFiles(e.target.files);
  });

  function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
  }

  function highlight(e) {
    dropZone.classList.add('dragover');
  }

  function unhighlight(e) {
    dropZone.classList.remove('dragover');
  }

  function handleDrop(e) {
    const dt = e.dataTransfer;
    const files = dt.files;
    handleFiles(files);
  }

  function handleFiles(files) {
    if (files.length === 0) return;

    const formData = new FormData();
    formData.append('file', files[0]);

    // 获取当前页面的 URL 对象
    const url = new URL(window.location.href);

    // 使用 URLSearchParams 解析查询参数
    const params = new URLSearchParams(url.search);

    // 检查是否存在 'name' 参数
    if (params.has('app')) {
      const nameValue = params.get('app');
      // 将 'name' 的值添加到 formData 的 'app' 字段中
      formData.append('app', nameValue);
    }


    uploadStatus.className = '';
    uploadStatus.textContent = '上传中...';

    const progressBar = document.getElementById('progress');

    fetch('/updates/upload', {
      method: 'POST',
      body: formData,
      onUploadProgress: (progressEvent) => {
        const progress = (progressEvent.loaded / progressEvent.total) * 100;
        progressBar.style.width = `${progress}%`;
      }
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          uploadStatus.className = 'success';
          uploadStatus.textContent = `上传成功！文件地址: ${data.url}`;
          progressBar.style.width = '100%';
        } else {
          throw new Error(data.message || '上传失败');
        }
      })
      .catch(error => {
        uploadStatus.className = 'error';
        uploadStatus.textContent = `上传失败: ${error.message}`;
        progressBar.style.width = '0%';
      });
  }
});